package com.jiunuan.live.core.server.handler.impl;

import com.alibaba.fastjson.JSON;
import com.jiunuan.live.core.server.common.ImContextUtils;
import com.jiunuan.live.core.server.common.ImMsg;
import com.jiunuan.live.core.server.handler.SimplyHandler;
import com.jiunuan.live.core.server.service.IMsgAckCheckService;
import com.jiunuan.live.im.dto.ImMsgBody;
import io.netty.channel.ChannelHandlerContext;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @Author: JiuNuan
 * @CreateTime: 2024-08-17 11:00
 * @Description: ack消息包，用于接收客户端的ack消息，
 *  客户端收到服务端发送的消息后，发送ack消息给服务端，服务端收到ack消息后，删除对应的消息
 */
@Slf4j
@Component
public class AckImMsgHandler implements SimplyHandler {
    @Resource
    private IMsgAckCheckService msgAckCheckService;
    /**
     * 消息处理函数，根据code匹配不同实现类
     *
     * @param ctx
     * @param imMsg
     */
    @Override
    public void handler(ChannelHandlerContext ctx, ImMsg imMsg) {
        Long userId = ImContextUtils.getUserId(ctx);
        Integer appId = ImContextUtils.getAppId(ctx);
        if(userId == null || appId == null){
            ctx.close();
            log.error("[AckImMsgHandler] attr error,imMsg: {}", imMsg);
            throw new RuntimeException("[AckImMsgHandler] attr error");
        }
        msgAckCheckService.doMsgAck(JSON.parseObject(imMsg.getBody(), ImMsgBody.class));
    }
}
